package com.jpa.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jpa.entity.AccountInfo;
import com.jpa.entity.Person;

public class UserDaoImpl implements UserDao {

	private EntityManagerFactory emf = Persistence.createEntityManagerFactory("mysqlJPA");
	private EntityManager em = emf.createEntityManager();

	@Override
	public AccountInfo save(AccountInfo accountInfo) {
		em.getTransaction().begin();
		em.persist(accountInfo);
		em.getTransaction().commit();
		emf.close();
		return accountInfo;
	}

	@Override
	public List<AccountInfo> findAll() {
		// AccountInfo为t_accountinfo映射的实体类
		Query query = em.createQuery("from AccountInfo");
		List<AccountInfo> list = query.getResultList();
		em.close();
		return list;
	}

	@Override
	public AccountInfo findById(int accountId) {
		AccountInfo accountInfo = em.find(AccountInfo.class, accountId);
		return accountInfo;
	}

	@Override
	public void remove(int accountId) {
		em.getTransaction().begin();
		AccountInfo  accountInfo = em.find(AccountInfo.class, accountId);
		em.remove(accountInfo); // 删除实体
		em.getTransaction().commit();
		
	}

	@Override
	public void update(AccountInfo accountInfo) {
		em.getTransaction().begin();  
        em.merge(accountInfo);
        em.getTransaction().commit();   
		
	}

}
